package cn.edu.scau.cmi.duke.comprehensive;
import cn.edu.scau.cmi.duke.mybatis.dao.StudentMapper;
import cn.edu.scau.cmi.duke.mybatis.dao.TeacherMapper;
import cn.edu.scau.cmi.duke.mybatis.entity.Student;
import cn.edu.scau.cmi.duke.mybatis.entity.StudentEntity;
import cn.edu.scau.cmi.duke.mybatis.entity.Teacher;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;




public class MybatisController implements Initializable {
	 @FXML
	    private TableView<StudentEntity> studentTable;
	    @FXML
	    private TableView<Teacher> teacherTable;
	    
	    @FXML
	    private TextField stuField;
	    @FXML
	    private TextField teaField;
	    
	    @FXML
	    private TextField stuIdField;
	    @FXML
	    private TextField stuNameField;
	    @FXML
	    private TextField stuTutorField;
	    
//	    @FXML
//	    private TextField teaIdField; 
	    @FXML
	    private TextField teaNameField;
	    
	    private ObservableList<StudentEntity> studentData = FXCollections.observableArrayList();
	    private ObservableList<Teacher> teacherData = FXCollections.observableArrayList();
	    
	    private List<StudentEntity> studentList =null;
	    private  List<Teacher> teacherList=null;
	    
	   private StudentMapper studentMapper;	   
	   private TeacherMapper teacherMapper;
	    
	  private  List<StudentEntity> list;  
	  private  List<Teacher> tealist;
	  //表格中的编辑列
	    private TableColumn<StudentEntity, StudentEntity> editCol = new TableColumn<>("操作");
	    private TableColumn<StudentEntity, StudentEntity> delCol = new TableColumn<>("操作");
	    
	    private TableColumn<Teacher, Teacher> editCol1= new TableColumn<>("操作");
	    private TableColumn<Teacher, Teacher> delCol1= new TableColumn<>("操作");
 
	    @Override
	    public void initialize(URL location, ResourceBundle resources) {
	    	InputStream in=null;
			try {
				in = Resources.getResourceAsStream("mybatis-config.xml");
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			SqlSessionFactory factory = builder.build(in);
			//开启自动提交事务
			SqlSession session=factory.openSession(true);
			 studentMapper=session.getMapper(StudentMapper.class);
			 teacherMapper=session.getMapper(TeacherMapper.class);
			  getAllStudents();
			  //teacherlist= teacherMapper.listTeachers();
			  getAllTeachers();
			  
	        initTable();
	        initTeacherTable();
	    }
	    
	

		private void initTeacherTable() {
			// TODO Auto-generated method stub
			   teacherTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
		    	  getAllTeachers();
		    	   showTeacherData(teacherList);
		    	   
		         delCol1.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue()));
		         delCol1.setCellFactory(param -> new TableCell<Teacher, Teacher>() {
		             private final Button deleteButton=new Button("删除"); 

		             @Override
		             protected void updateItem(Teacher teacher, boolean empty) {
		                 super.updateItem(teacher, empty);
		                 if (teacher== null) {
		                     setGraphic(null);
		                     return;
		                 }
		                 setGraphic(deleteButton);
		                 //点击删除按钮，需要将这一行从表格移除，同时从底层数据库真正删除
		                 deleteButton.setOnAction(event -> {
		                     Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
		                     alert.setTitle("确认对话框");
		                     alert.setHeaderText("工号:"+teacher.getId()+"姓名:" + teacher.getName());
		                     alert.setContentText("确定要删除该教师记录吗?");
		                     Optional<ButtonType> result = alert.showAndWait();
		                     //点击了确认按钮，执行删除操作，同时移除一行模型数据
		                     if (result.get() == ButtonType.OK) {
		                    	 teacherMapper.deleteTeacher(teacher.getId());
		                      getAllTeachers();
		                      showTeacherData( teacherList);
		                   
		                     }
		                 });
		             }
		             
		         });
		         //将除列加入图书表格
		         teacherTable.getColumns().add(delCol1);
		}

		
		private void initTable() {
	    	   studentTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
	    	  getAllStudents();
	    	   showStudentData( studentList);
	    	   
	         delCol.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue()));
	         delCol.setCellFactory(param -> new TableCell<StudentEntity, StudentEntity>() {
	             private final Button deleteButton=new Button("删除"); 

	             @Override
	             protected void updateItem(StudentEntity student, boolean empty) {
	                 super.updateItem(student, empty);
	                 if (student == null) {
	                     setGraphic(null);
	                     return;
	                 }
	                 setGraphic(deleteButton);
	                 //点击删除按钮，需要将这一行从表格移除，同时从底层数据库真正删除
	                 deleteButton.setOnAction(event -> {
	                     Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
	                     alert.setTitle("确认对话框");
	                     alert.setHeaderText("学号:"+student.getNumber()+"姓名:" + student.getName());
	                     alert.setContentText("确定要删除该学生记录吗?");
	                     Optional<ButtonType> result = alert.showAndWait();
	                     //点击了确认按钮，执行删除操作，同时移除一行模型数据
	                     if (result.get() == ButtonType.OK) {
	                      studentMapper.deleteStudent(student.getId());
	                      getAllStudents();
	                      showStudentData(studentList);
	                   
	                     }
	                 });
	             }
	             
	         });
	         //将除列加入图书表格
	         studentTable.getColumns().add(delCol);
	       
	    }
		

	    
		private void showStudentData(List<StudentEntity> studentList) {
			// TODO Auto-generated method stub
			studentData.clear();
			studentData.addAll(studentList);
		       studentTable.setItems(studentData);
		}

		private void getAllStudents() {
			// TODO Auto-generated method stub
			 list=studentMapper.listStudentEntitys();
			studentList= new ArrayList<>();
			studentList.clear();
			for(StudentEntity student:list) {
				StudentEntity stu=new StudentEntity();
				stu.setId(student.getId());
				stu.setName(student.getName());
				stu.setNumber(student.getNumber());
				stu.setTutor(student.getTutor());
				studentList.add(stu);
			}
			
		
		}
		
		private void showTeacherData(List<Teacher> teacherList) {
			// TODO Auto-generated method stub
			teacherData.clear();
			teacherData.addAll(teacherList);
			teacherTable.setItems(teacherData);
		}
		
	   private void getAllTeachers() {
					// TODO Auto-generated method stub
	    	 tealist=teacherMapper.listTeachers();
	    	 teacherList= new ArrayList<>();
	    	 teacherList.clear();
				for(Teacher teacher: tealist) {
					Teacher tea=new Teacher();
					tea.setId(teacher.getId());
					tea.setName(teacher.getName());
					
					teacherList.add(tea);
					showTeacherData(teacherList);
				}
				
		}
		
	   public void addStudent() {
//	    	@FXML
//		    private TextField stuIdField;学号
//		    @FXML
//		    private TextField stuNameField;姓名
//		    @FXML
//		    private TextField stuTutorField;指导老师工号
	    	String keyword=null;
	    	keyword =  stuIdField.getText().trim();
	         long number=Long.parseLong(keyword);
	         
	         String name =  stuNameField.getText().trim();
	         
	         keyword =  stuTutorField.getText().trim();
	         long tutor=Long.parseLong(keyword);
	       
	         
	         Student student=new Student();
	         student.setName(name);
	         student.setNumber(number);
	         student.setTutor(tutor);
	         
	         studentMapper.saveStudent(student);
	         getAllStudents() ;
	         showStudentData(studentList) ;
	         showTeacherData(teacherList) ;
	    	
	    }
      public void addTeacher() {
//    	  @FXML
//  	    private TextField teaIdField; 
//  	    @FXML
//  	    private TextField teaNameField;
    		 String name =  teaNameField.getText().trim();
    		 
    		 Teacher teacher=new Teacher();
    		 teacher.setName(name);
    		 teacherMapper.saveTeacher(teacher);
    		 
    		 getAllTeachers();
	    	
	    }
	    
	    public void findSingleStudent() {
	    	 String keywords =  stuField.getText().trim();
	
	         Long number=Long.parseLong(keywords);
	         studentList.clear();
	         for(StudentEntity student:list) {
	        	 if(student.getNumber()==number) {
	        		 StudentEntity stu=new StudentEntity();
	 				stu.setId(student.getId());
	 				stu.setName(student.getName());
	 				stu.setNumber(student.getNumber());
	 				stu.setTutor(student.getTutor());
	 				studentList.add(stu);
	        	 }
	         }
	         
	         showStudentData(studentList) ;
	       
	    }
	   public void findAllStudent() {
	    	getAllStudents();
	    	showStudentData(studentList);
	    }

	   public void findSingleTeacher() {
	    	 String keywords =  teaField.getText().trim();
	         Long id=Long.parseLong(keywords);
	         teacherList.clear();
	         for(Teacher teacher:tealist) {
	        	 if(teacher.getId()==id) {
	        		 Teacher tea=new Teacher();
	 				tea.setId(teacher.getId());
	 				tea.setName(teacher.getName());	 			
	 				teacherList.add(tea);
	 				break;
	        	 }
	         }
	         
	         showTeacherData(teacherList);
	       
	    }
	   public void findAllTeacher() {
	    	getAllTeachers();
	    	  showTeacherData(teacherList);
	    }

}
